package com.qianwei.footpath.ui;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.common.baselib.mvp.MvpBasePresenter;
import com.common.baselib.ui.ToastUtil;
import com.qianwei.footpath.R;
import com.qianwei.footpath.base.BaseActivity;
import com.qianwei.footpath.event.SerialPortEvent;
import com.qianwei.footpath.manage.DataManager;
import com.qianwei.footpath.manage.LocalCacheDataManage;
import com.qianwei.footpath.manage.SerialPortManager;
import com.qianwei.footpath.manage.TimerManager;
import com.qianwei.footpath.utils.TextToSpeechUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

public class TestC extends BaseActivity {
    private static final String TAG = "Test---";
    private TextToSpeechUtils ttsUtils;
    private int testDownLoadTime = 30;
    private int balance_force = 20;
    private ImageView ivXuHua, ivRen;
    private TextView ivTitle, tv_result, tvDown;
    private TimerTask testRealTimeWeightTimeTask;
    private List<Double> weights = new ArrayList<>();
    private boolean isTesting = false;
    private int secondsPassed = 0;
    @Override
    protected int layoutId() {
        return R.layout.c_activity;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        ivTitle = findViewById(R.id.ivTitle);
        ivXuHua = findViewById(R.id.ivXuHua);
        tvDown = findViewById(R.id.tvDown);
        tv_result = findViewById(R.id.tv_result);
        ivRen = findViewById(R.id.ivRen);

        ivRen.setImageResource(R.drawable.ic_ren3);
        ivTitle.setText("平衡力测量");
        tv_result.setText("闭眼单腿");

        testDownLoadTime = LocalCacheDataManage.getLocalConfigData().getPhysical_test_timeout();
        balance_force = LocalCacheDataManage.getLocalConfigData().getBalance_force();

        startZoomAnimation();
        initTTS();
    }

    private void initTTS() {
        ttsUtils = new TextToSpeechUtils(this, new TextToSpeechUtils.OnInitListener() {
            @Override
            public void onInitSuccess() {
                speak("请您双手合十，紧闭双眼，保持单腿站立，开始平衡力测试", "101");
                Log.e(TAG, "发送称重指令");
                SerialPortManager.getInstance(getContext()).sendRealTimeWeightCommand();
                stopTimeTask(testRealTimeWeightTimeTask);
                startTestRealTimeWeightTimeTask();
            }

            @Override
            public void onInitFailed(int errorCode) {
                Log.e(TAG, "TTS初始化失败");
                showToast("语音播报初始化失败");
                Log.e(TAG, "发送称重指令");
                SerialPortManager.getInstance(getContext()).sendRealTimeWeightCommand();
                stopTimeTask(testRealTimeWeightTimeTask);
                startTestRealTimeWeightTimeTask();
            }
        });

    }

    private void speak(String text, String utteranceId) {
        ttsUtils.speak(text, utteranceId, null);
    }


    private void showToast(String message) {
        runOnUiThread(() -> Toast.makeText(this, message, Toast.LENGTH_SHORT).show());
    }

    private void startZoomAnimation() {
        ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(ivXuHua, "scaleX", 1f, 1.1f);
        ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(ivXuHua, "scaleY", 1f, 1.1f);
        scaleXAnimator.setDuration(800);
        scaleYAnimator.setDuration(800);
        scaleXAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        scaleYAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        scaleXAnimator.setRepeatCount(ValueAnimator.INFINITE);
        scaleYAnimator.setRepeatCount(ValueAnimator.INFINITE);
        scaleXAnimator.setRepeatMode(ValueAnimator.REVERSE);
        scaleYAnimator.setRepeatMode(ValueAnimator.REVERSE);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(scaleXAnimator, scaleYAnimator);
        animatorSet.start();
    }

    private void startTestRealTimeWeightTimeTask() {
        if (testRealTimeWeightTimeTask == null) {
            Log.e(TAG, "一次体重定时器");
            testRealTimeWeightTimeTask = new TimerTask() {

                @Override
                public void run() {
                    secondsPassed++;
                    runOnUiThread(() -> {
                        int dif = testDownLoadTime - secondsPassed;
                        tvDown.setText(dif + "s");
                        if (!isTesting) {
                            isTesting = true;
                            SerialPortManager.getInstance(getContext()).sendRealTimeWeightCommand();
                        }
                    });
                    if(secondsPassed >= testDownLoadTime && weights.size() >= 20){
                        runOnUiThread(() -> {
                            Log.e(TAG, "测量完成");
                            startActivity(new Intent(getContext(), TestResult.class));
                            finish();
                        });
                        return;
                    }
                    if (secondsPassed >= testDownLoadTime) {
                        finish();
                    }
                }
            };
            TimerManager.getInstance().startTimer(1000, 1000, testRealTimeWeightTimeTask); // 每秒执行一次
        }
    }

    private void stopTimeTask(TimerTask timerTask) {
        if (timerTask != null) {
            TimerManager.getInstance().stopTimer(timerTask);
            timerTask.cancel();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRealTimeWeightReceived(SerialPortEvent.RealTimeWeightEvent event) {
        double weight = event.value;
        Log.e(TAG, "测量一次体重完成: " + weight);
        weights.add(weight);
        if (weight > 0) {

            if (secondsPassed >= balance_force) {
                stopTimeTask(testRealTimeWeightTimeTask);

                DataManager.getInstance().setWeights(weights);

                new Handler().postDelayed(() -> {
                    startActivity(new Intent(getContext(), TestResult.class));
                    finish();
                }, 1000);

            }
        }
        isTesting = false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onError(SerialPortEvent.ErrorEvent event) {
        ToastUtil.showToastLong(getContext(), "报错：" + event.message);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onProtocolError(SerialPortEvent.ProtocolErrorEvent event) {
        ToastUtil.showToastLong(getContext(), "报错：errorCode=" + event.errorCode + ",errorMsg=" + event.errorMsg);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (ttsUtils != null) {
            ttsUtils.release();
            ttsUtils = null;
        }
        stopTimeTask(testRealTimeWeightTimeTask);
        SerialPortManager.getInstance(getContext()).release();
        super.onDestroy();
    }

    @Override
    protected MvpBasePresenter createPresenter() {
        return null;
    }
}
